package utils

import (
	"crypto/md5"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"math/big"
)

// 字符串操作相关工具包
// ContainsKeyInSlice checks if the key of the map is present in the slice of strings
func ContainsKeyInSlice(m map[string]interface{}, keys []string) bool {
	// 将 keys 切片转换为一个 map
	keysMap := make(map[string]struct{})
	for _, key := range keys {
		keysMap[key] = struct{}{}
	}

	// 检查 map 中的每个键是否存在于 keysMap 中
	for key := range m {
		if _, found := keysMap[key]; found {
			return false
		}
	}
	return true
}

// 判断字符串是否空
func IsEmpty(s string) bool {
	return len(s) == 0
}

// 判断字符串不为空时
func IsNotEmpty(s string) bool {
	return len(s) > 0
}

// MD5加密
func HashMd5(str string) string {
	hasher := md5.New()
	hasher.Write([]byte(str))
	return hex.EncodeToString(hasher.Sum(nil))
}

// 密码加密
func PasswordMd5ToString(str, salt string) string {
	if IsEmpty(str) {
		str = "123456"
	}
	return HashMd5(fmt.Sprintf("%s%s", HashMd5(str), salt))
}

// 生成指定长度的随机字符串
func GenerateRandomString(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	var result string
	for i := 0; i < length; i++ {
		n, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
		if err != nil {
			panic(err)
		}
		result += string(charset[n.Int64()])
	}
	return result
}
